package xuanmu.office.excel.data.generator.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import xuanmu.office.excel.data.generator.entity.Truck;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public final class TruckDao {

    @Value("${custom.vehicle-info.src}")
    private String csvFilePath;

    public List<Truck> list() {
        List<Truck> truckList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(csvFilePath), "UTF-8"))) {

            String line;
            while ((line = br.readLine()) != null) {
                // 处理可能的 BOM 头（如果文件是 UTF-8 with BOM）
                line = removeBOM(line);

                // 使用更健壮的 CSV 解析（防止逗号在字段内）
                String[] values = parseCsvLine(line);

                if (values.length < 3) {
                    continue; // 如果列数不足 3，跳过该行
                }

                Truck truck = new Truck(values[0].trim(), values[1].trim(), Double.parseDouble(values[2].trim()));
                truckList.add(truck);
            }
        } catch (IOException e) {
            System.err.println("【错误】无法读取 CSV 文件：" + csvFilePath);
            System.err.println("【提示】请检查文件路径、编码（UTF-8）及内容格式");
            e.printStackTrace();
            System.exit(1);
        } catch (NumberFormatException e) {
            System.err.println("【错误】B 或 C 列不是有效的数字");
            e.printStackTrace();
            System.exit(1);
        }



//        try (BufferedReader br = new BufferedReader(
//                new InputStreamReader(new FileInputStream(csvFilePath), "GBK"))) {
////            try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
//            String line;
//            while ((line = br.readLine()) != null) {
//                String[] values = line.split(",");
//                if (values.length != 3) {
//                    continue; // 如果数组长度不是3，则跳过该行
//                }
//                Truck truck = new Truck(values[0].trim(), values[1].trim(), Double.parseDouble(values[2].trim()));
//                truckList.add(truck);
//            }
//        } catch (IOException e) {
//            System.err.println("【错误】无法读取【车辆信息配置文件】：" + csvFilePath);
//            System.err.println("【提示】请检查【application.properties】中的配置，确保文件存在且可读");
//            System.exit(0);
//        }
//        System.out.println("【系统】读取到【" + truckList.size() + "】条车辆信息，数据来源：" + csvFilePath);
//        if (truckList.size() == 0) {
//            System.err.println("【错误】无法读取到有效的车辆信息，请检查配置！");
//            System.exit(0);
//        }
        return truckList;
    }

    private static String[] parseCsvLine(String line) {
        List<String> values = new ArrayList<>();
        boolean inQuotes = false;
        StringBuilder currentValue = new StringBuilder();

        for (char c : line.toCharArray()) {
            if (c == '"') {
                inQuotes = !inQuotes; // 切换引号状态
            } else if (c == ',' && !inQuotes) {
                values.add(currentValue.toString());
                currentValue = new StringBuilder();
            } else {
                currentValue.append(c);
            }
        }
        values.add(currentValue.toString()); // 添加最后一个字段

        return values.toArray(new String[0]);
    }

    /**
     * 移除 UTF-8 BOM 头（如果存在）
     */
    private static String removeBOM(String line) {
        if (line.startsWith("\uFEFF")) {
            return line.substring(1);
        }
        return line;
    }

}
